﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OneOfAll.Common.Util
{
    /// <summary>
    /// 全局异常处理帮助类
    /// </summary>
    public class ExceptionHelper
    {
        public static event Action<string, string> WarnEvent;

        /// <summary>
        /// 显示异常信息到UI
        /// </summary>
        /// <param name="e"></param>
        /// <param name="isInvoke">默认是同步，阻碍线程</param>
        public static void Show(Exception e, bool isInvoke = true)
        {
            StringBuilder excAddrBuilder = new StringBuilder();
            e?.StackTrace?.Split("\r\n".ToArray())?.ToList()?.ForEach(item =>
            {
                if (item.Contains("行号") || item.Contains("line"))
                    excAddrBuilder.Append($"    {item}\r\n");
            });

            string addr = excAddrBuilder.ToString();
            if (isInvoke)
            {
                WarnEvent?.Invoke($"{addr}", e.Message);
            }
            else
            {
                WarnEvent?.BeginInvoke($"{addr}", e.Message, null, null);
            }
        }

        public static void Show(string addr, string warnstr, bool isInvoke = true)
        {
            if (isInvoke)
            {
                WarnEvent?.Invoke(addr, warnstr);
            }
            else
            {
                WarnEvent?.BeginInvoke(addr, warnstr, null, null);
            }
        }


    }
}
